package org.jgs1904.chanmufeng;

import java.io.FileOutputStream;
import java.io.Serializable;
import java.io.File;
import java.io.OutputStream;
import java.io.ObjectOutputStream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

/**
 * 可序列化的单例
 *
 * @author: 默苍璃
 * @date: 2024-07-01 14:07
 */

public class SeriableSingleton implements Serializable {
    // 类初始化的时候便进行对象实例化
    private static final SeriableSingleton hungrySingleton = new SeriableSingleton();

    private SeriableSingleton() {
    }

    public static SeriableSingleton getInstance() {
        return hungrySingleton;
    }

    //只需要添加这一个函数即可
    private Object readResolve() {
        return hungrySingleton;
    }
}


/**
 * 序列化破坏单例
 */
class SingletonBrokenBySerializing {

    public static void main(String[] args) {
        SeriableSingleton s1 = SeriableSingleton.getInstance();
        SeriableSingleton s2 = null;

        FileOutputStream fos = null;
        try {
            File file;
            fos = new FileOutputStream("SeriableSingleton.obj");
            OutputStream out;
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(s1);
            oos.flush();
            oos.close();
            fos.close();

            FileInputStream fis = new FileInputStream("SeriableSingleton.obj");
            ObjectInputStream ois = new ObjectInputStream(fis);
            s2 = (SeriableSingleton) ois.readObject();
            ois.close();
            fis.close();


            // 输出为false
            System.out.println(s1 == s2);
        } catch (Exception e) {

        }
    }

}
